<template>
  <div class="doc-left-main">
    <header class="right-header">
      <div class="title">{{ headerName }}</div>
      <div class="btn" @click="dialogVisible = true">
        <i class="iconfont icona-xinzengyuanjiao"></i>
      </div>
    </header>
    <el-scrollbar class="right-body" v-loading="loading">
      <!-- 文件-内容 -->
      <div class="file-list" v-if="headerName === '全部' || headerName === '我的'">
        <div class="file-box" v-for="item in docListData" :key="item.id" @click="toDetail(item)">
          <!-- 下拉选择框 -->
          <el-dropdown size="large" @command="(command:string) => {handleCommand(command,item)}">
            <div class="icon-box">
              <i class="iconfont icongengduomore"></i>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="reName"
                  ><i class="iconfont iconwangpan-zhongmingming1x"></i>重命名</el-dropdown-item
                >
                <el-dropdown-item divided command="delete"
                  ><i style="color: red" class="iconfont iconwangpan-cuohao1x"></i
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <svg class="color-icon" aria-hidden="true">
            <use xlink:href="#iconwenjianjia"></use>
          </svg>
          <div class="file-bottom">
            <p class="file-name">{{ item.fileName }}</p>
            <p class="create-time">{{ item.created_at }}</p>
          </div>
        </div>
      </div>
      <div class="recently-list" v-if="headerName === '最近'">
        <Recently :recodeFileData="recodeFileData"></Recently>
      </div>
      <div class="like-list" v-if="headerName === '收藏'">
        <Collect :likeListData="likeListData"></Collect>
      </div>
    </el-scrollbar>
    <!-- 新增文件夹 -->
    <el-dialog v-model="dialogVisible" width="50%" top="10vh" :show-close="false" draggable>
      <AddDialog
        v-if="dialogVisible"
        @dialogSave="handleDialogSave"
        :dialogVisible="dialogVisible"
      ></AddDialog>
    </el-dialog>
    <!-- 重命名 -->
    <el-dialog
      :lock-scroll="false"
      v-model="reNameDialogVisible"
      title="重命名"
      width="430px"
      min-width="430px"
    >
      <el-form :model="reFileData" @submit.prevent="" @keydown.enter="handleSubmitReName">
        <el-form-item>
          <el-input v-model="reFileData.fileName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click.stop="reNameDialogVisible = false">取消</el-button>
          <el-button color="#6C52EA" @click.stop="handleSubmitReName"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

import AddDialog from './AddDialog.vue'
import Recently from './Recently.vue'
import Collect from './Collect.vue'

import { useRouter } from 'vue-router'

import { editDocumentData, deleteDocumentData, getDocumentList } from '@/apis/system/document'

// import { IfileListData } from '@/views/system/docCenter/config/fileListData'

import Bus from '@/utils/bus'

import { store } from '@/store/doc-center'
import { storeToRefs } from 'pinia'
import { IfileListData } from '../config/fileListData'
import { getRecordList } from '@/apis/system/docRecord'

const docStore = store()
const { docListData, allDocListData, loading } = storeToRefs(docStore)

const dialogVisible = ref(false)

const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

/**
 * @desc: 获取右侧文件数据，并存入状态管理器
 */
onMounted(async () => {
  await docStore.getData()
})

/**
 * @desc: 保存关闭
 */
const handleDialogSave = () => {
  dialogVisible.value = false
  docStore.getData()
}

/**
 * @desc: 获取管理员和可查看人员
 *
 */
// let personListData = ref()
// const handleAddFile = () => {
//   let params = {}
//   getPageList(params).then((res) => {
//     if (res.data && res.code !== 200) return
//     personListData.value = res.data?.data
//   })
// }

/**
 * @desc: 最近浏览
 */
const recodeFileData = ref<IfileListData[]>()
const params = ref({
  pageSize: 100
})
const getRecodeData = () => {
  loading.value = true
  getRecordList(params.value)
    .then((res) => {
      if (!res) return
      res.rows.forEach((element: IfileListData) => {
        element.created_at = new Date(
          +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
        )
          .toISOString()
          .replace(/T/g, ' ')
          .replace(/\.[\d]{3}Z/, '')
      })
      recodeFileData.value = res.rows.filter((element: { user_id: number }) => element.user_id === getUserInfo.value.id)
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * @desc: 下拉菜单指令
 */
const handleCommand = (command: string, item: IfileListData) => {
  switch (command) {
    case 'reName': {
      handleRename(item)
      break
    }
    case 'delete': {
      hadleDelete(item)
      break
    }
  }
}

/**
 * @desc: 重命名
 */
let reFileData = ref({
  fileName: '',
  _id: 0
})
const reNameDialogVisible = ref(false)
const handleRename = (item: { fileName: string; id: number }) => {
  reFileData.value = {
    fileName: item.fileName,
    _id: item.id
  }
  reNameDialogVisible.value = true
}

/**
 * @desc: 重命名保存
 */
const handleSubmitReName = () => {
  editDocumentData(reFileData.value)
    .then((res) => {
      if (!res) return
      docStore.getData()

      ElMessage.success('修改成功')
    })
    .catch(() => {
      ElMessage('服务器内部错误！')
    })
  reNameDialogVisible.value = false
}

/**
 * @desc: 删除文件
 */
const hadleDelete = (item: IfileListData) => {
  ElMessageBox.confirm(`是否删除名为 ${item.fileName} 的文件夹?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    lockScroll: false
  })
    .then(() => {
      deleteDocumentData(item.id).then((res) => {
        if (!res) return
        docStore.getData()
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

/**
 * @desc: 获取收藏列表
 */
let findLikeListData: IfileListData[] = []
const _findFIle = (item: IfileListData[]) => {
  for (let i = 0; i < item.length; i++) {
    item[i].doc_collect?.map((res) => {
      if (res.is_status === 1 && res.user_id === getUserInfo.value.id) {
        findLikeListData.push(item[i])
      }
    })
    if (item[i].children_file && item[i].children_file.length) {
      _findFIle(item[i].children_file)
    }
  }
}

const likeListData = ref<IfileListData[]>()
const getLikeData = () => {
  findLikeListData = [] as IfileListData[]
  _findFIle(docListData.value)
  likeListData.value = findLikeListData
}

/**
 * @desc: 点击进入详情页面
 */
const router = useRouter()
const toDetail = (item: IfileListData) => {
  router.push({
    name: 'DocDetails',
    query: {
      parent_id: item.id,
      name: item.fileName,
      descs: item.descs,
      userId: item.user_id
    }
  })
}

/**
 * @desc: 点击左侧筛选右侧
 */
const headerName = ref('全部')
Bus.on('click-show-all', function (item: { name: string }) {
  headerName.value = item.name
  docStore.getData()
})

Bus.on('click-show-my', (item: { name: string }) => {
  headerName.value = item.name
  let params = {
    user_id: getUserInfo.value.id
  }
  docStore.getData(params)
})

Bus.on('click-show-recently', (item: { name: string }) => {
  headerName.value = item.name
  getRecodeData()
})

Bus.on('click-show-like', (item: { name: string }) => {
  headerName.value = item.name
  getLikeData()
})

// 分类筛选
Bus.on('send-click-node', (res: { type: string }) => {
  docStore.getData({
    type: res.type
  })
})

/**
 * @desc: 记得取消事件，避免造成多次触发
 */
onBeforeUnmount(() => {
  Bus.off('click-show-all')
  Bus.off('click-show-my')
  Bus.off('click-show-recently')
  Bus.off('click-show-like')
  Bus.off('send-click-node')
})
</script>

<style lang="less" scoped>
:deep(.el-dialog) {
  border-radius: 10px;
}
.doc-left-main {
  display: flex;
  flex-direction: column;
  height: 100%;
  .right-header {
    display: flex;
    padding-bottom: 10px;
    justify-content: space-between;
    line-height: 40px;
    height: 40px;
    border-bottom: 1px solid #f1f1f1;
    .title {
      font-size: 20px;
      font-weight: 600;
    }
    .btn {
      width: 40px;
      border-radius: 50%;
      text-align: center;
      background-color: #6c52ea;
      &:hover {
        background-color: #6c52ea;
        cursor: pointer;
      }
      .iconfont {
        font-size: 20px;
        color: #fff;
      }
    }
  }
  .right-body {
    padding-top: 10px;
    height: 0;
    flex-grow: 1;
    flex-shrink: 0;
    .file-list {
      display: flex;
      flex-wrap: wrap;
      overflow-y: auto;
      // min-width: 910px;
      .file-box {
        position: relative;
        width: 150px;
        min-height: 150px;
        margin: 0 50px 30px 0;
        display: flex;
        flex-direction: column;
        align-content: center;
        text-align: center;
        justify-content: center;
        .icon-box {
          position: absolute;
          left: 120px;
          top: 5px;
          width: 25px;
          height: 25px;
          background: #fff;
          border-radius: 5px;
          visibility: hidden;
          .iconfont {
            line-height: 25px;
            font-size: 20px;
          }
        }
        &:hover {
          background: #f0f4fd;
          border-radius: 10px;
          cursor: pointer;
        }
        &:hover .icon-box {
          visibility: visible;
        }

        .color-icon {
          height: 130px;
        }
        .file-bottom {
          padding-bottom: 10px;

          .file-name {
            padding-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .create-time {
            font-size: 10px;
            color: #25282e;
          }
        }
      }
    }
    .like-list {
      .file-name-warp {
        display: flex;
        align-items: center;
        .file-name {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
